package com.atguigu.yygh.user.service.impl;


import com.atguigu.yygh.enums.AuthStatusEnum;
import com.atguigu.yygh.enums.StatusEnum;
import com.atguigu.yygh.exception.YyghException;
import com.atguigu.yygh.model.user.Patient;
import com.atguigu.yygh.model.user.UserInfo;
import com.atguigu.yygh.user.mapper.UserInfoMapper;
import com.atguigu.yygh.user.service.PatientService;
import com.atguigu.yygh.user.service.UserInfoService;
import com.atguigu.yygh.utils.JwtHelper;
import com.atguigu.yygh.vo.user.LoginVo;
import com.atguigu.yygh.vo.user.UserAuthVo;
import com.atguigu.yygh.vo.user.UserInfoQueryVo;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2025-03-19
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private PatientService patientService;
    @Override
    public Map<String, Object> login(LoginVo loginVo) {
        if (loginVo == null) {
            throw new YyghException(20001, "登录参数不能为空");
        }
        String phone = loginVo.getPhone();
        String code = loginVo.getCode();

        //校验参数
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)) {
            throw new YyghException(20001, "手机号或者验证码不能为空");
        }
        //校验校验验证码
        String existCode = redisTemplate.opsForValue().get(phone);
        if (StringUtils.isEmpty(existCode)||!code.equals(existCode)){
           throw new YyghException(20001, "验证码错误");
        }
        String openid = loginVo.getOpenid();
        if (StringUtils.isEmpty(openid)){
            //表示非微信登录,手机号登录
            QueryWrapper<UserInfo> infoQueryWrapper = new QueryWrapper<>();
            infoQueryWrapper.eq("phone", phone);
            //获取会员
            UserInfo userInfo  = userInfoMapper.selectOne(infoQueryWrapper);

            if (userInfo  == null) {
                //第一次登录
                userInfo = new UserInfo();
                //保存到数据库
                userInfo.setPhone(phone);
                userInfo.setCreateTime(new Date());
                userInfo.setStatus(1);
                this.save(userInfo);
            }
            //校验是否被禁用
            if (userInfo.getStatus() == 0) {
                throw new YyghException(20001, "用户已被禁用");
            }
            return get(userInfo);
        }else {
            //微信登录
            UserInfo userInfoFinal  = new UserInfo();
            // 如果查询到手机号对应数据,封装到userInfoFinal
            UserInfo userInfoByPhone = userInfoMapper.selectOne(new QueryWrapper<UserInfo>().eq("phone", phone));
            if (userInfoByPhone != null){
                BeanUtils.copyProperties(userInfoByPhone,userInfoFinal);
                //把手机号数据删除
                userInfoMapper.deleteById(userInfoByPhone.getId());
            }
            //3 根据openid查询微信信息
            UserInfo userInfoByOpenid = userInfoMapper.selectOne(new QueryWrapper<UserInfo>().eq("openid", openid));
            //4 把微信信息封装userInfoFinal
            userInfoFinal.setId(userInfoByOpenid.getId());
            userInfoFinal.setNickName(userInfoByOpenid.getNickName());
            userInfoFinal.setOpenid(userInfoByOpenid.getOpenid());
            //数据库表没有相同绑定手机号，设置值
            if (userInfoByPhone==null){
                userInfoFinal.setPhone(phone);
                userInfoFinal.setStatus(userInfoByOpenid.getStatus());
            }
            //修改手机号
            userInfoMapper.updateById(userInfoFinal);
            //5 判断用户是否锁定
            if (userInfoFinal.getStatus()==0){
                throw new YyghException(20001, "用户已被禁用");
            }
            //6 封装返回数据
            return get(userInfoFinal);

        }

    }

    @Override
    public UserInfo selectWxUserByOpenid(String openid) {
      return   userInfoMapper.selectOne(new QueryWrapper<UserInfo>().eq("openid", openid));



    }

    @Override
    public UserInfo getUserInfo(String token) {
        Long userId = JwtHelper.getUserId(token);
        if (userId == null){
            throw new YyghException(20001, "token无效");
        }
        UserInfo userInfo = userInfoMapper.selectById(userId);
        Map<String, Object> param = userInfo.getParam();
        param.put("authStatusString", AuthStatusEnum.getStatusNameByStatus(userInfo.getAuthStatus()));
        return userInfo;
    }

    @Override
    public void userAuth(UserAuthVo userAuthVo, String token) {
        Long userId = JwtHelper.getUserId(token);
        if (userId == null){
            throw new YyghException(20001, "token无效");
        }
        UserInfo userInfo = userInfoMapper.selectById(userId);
        //修改用户信息
        userInfo.setName(userAuthVo.getName());
        userInfo.setCertificatesType(userAuthVo.getCertificatesType());
        userInfo.setCertificatesNo(userAuthVo.getCertificatesNo());
        userInfo.setCertificatesUrl(userAuthVo.getCertificatesUrl());
        //认证状态: 0-未认证 1-认证中 2-已认证 (1)
        userInfo.setAuthStatus(AuthStatusEnum.AUTH_RUN.getStatus());
        userInfoMapper.updateById(userInfo);
    }

    @Override
    public Page<UserInfo> userListByCondition(Integer page, Integer limit, UserInfoQueryVo userInfoQueryVo) {
        //关键字
        String keyword = userInfoQueryVo.getKeyword();
        Page<UserInfo> userInfoPage = new Page<>(page, limit);
        QueryWrapper<UserInfo> infoQueryWrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(keyword)){
            infoQueryWrapper.like("name",keyword).or().like("phone",keyword);
        }
        if(!StringUtils.isEmpty(userInfoQueryVo.getStatus())){
            infoQueryWrapper.eq("status",userInfoQueryVo.getStatus());
        }
        if(!StringUtils.isEmpty(userInfoQueryVo.getAuthStatus())){
            infoQueryWrapper.eq("auth_status",userInfoQueryVo.getAuthStatus());
        }
        if(!StringUtils.isEmpty(userInfoQueryVo.getCreateTimeEnd())){
            //搜索时间大于创建时间
            infoQueryWrapper.ge("create_time",userInfoQueryVo.getCreateTimeBegin());
            //搜索时间小于等于创建时间
            infoQueryWrapper.le("create_time",userInfoQueryVo.getCreateTimeEnd());
        }
        Page<UserInfo> userInfoPage1 = userInfoMapper.selectPage(userInfoPage, infoQueryWrapper);
        //封装返回数据
        userInfoPage1.getRecords().forEach(item->{
            packageUserInfoParam(item);
        });
        return userInfoPage1;
    }

    @Override
    public void lockUser(String userId, Integer status) {
        UserInfo userInfo = userInfoMapper.selectById(userId);
        if (userInfo == null){
            throw new YyghException(20001, "用户不存在");
        }
        userInfo.setStatus(status);
        userInfoMapper.updateById(userInfo);
    }

    @Override
    public Map<String, Object> showUser(Long userId) {
        UserInfo userInfo = userInfoMapper.selectById(userId);
        packageUserInfoParam(userInfo);
        HashMap<String, Object> map = new HashMap<>();
        map.put("userInfo", userInfo);
        List<Patient> patientList = patientService.getPatientList(userId);
        map.put("patientList", patientList);
        return map;
    }

    @Override
    public void approval(Long id, Integer authStatus) {
        UserInfo userInfo = userInfoMapper.selectById(id);
        userInfo.setAuthStatus(authStatus);
        userInfoMapper.updateById(userInfo);
    }

    private void packageUserInfoParam(UserInfo userInfo) {
        //封装认证状态
        String authStatusString= AuthStatusEnum.getStatusNameByStatus(userInfo.getAuthStatus());
        String statusString= StatusEnum.getStatusNameByCode(userInfo.getStatus());
        userInfo.getParam().put("authStatusString", authStatusString);
        userInfo.getParam().put("statusString", statusString);
    }

    private Map<String, Object> get(UserInfo userInfo){
        //返回页面显示名称
        HashMap<String, Object> map = new HashMap<>();
        String name = userInfo.getName();
        if (StringUtils.isEmpty(name)) {
            name = userInfo.getNickName();
        }
        if (StringUtils.isEmpty(name)) {
            name = userInfo.getPhone();
        }
        map.put("name", name);
        //生成token
        String token = JwtHelper.createToken(userInfo.getId(), userInfo.getPhone());
        map.put("token", token);
        return map;
    }
}
